<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: skyblue;
            position: absolute;
        }
        button{
            position: absolute;
            right: 100px;
            top: 50%;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <button id="btn">回放</button>
    <script>
        var box = document.querySelector('.box')
        var btn = document.querySelector('#btn')
        let arr = []
        box.onmousedown = function (e) {
            var left = e.clientX - box.offsetLeft;
            var top = e.clientY - box.offsetTop;
            arr.unshift([box.offsetTop, box.offsetLeft]);
            console.log(arr);
            window.onmousemove = function (e) {
                // console.log(2);
                // 处理兼容问题
                e = e || window.event
                var x = e.clientX - box.offsetWidth / 2  //让光标在box 中间
                var y = e.clientY - box.offsetHeight / 2

                var l = e.clientX - left;
                var t = e.clientY - top;
                arr.unshift([t, l]);
                // 判断box是否超过页面可视区域
                if (x >= document.documentElement.clientWidth - box.offsetWidth) {
                    x = document.documentElement.clientWidth - box.offsetWidth
                }
                if (y >= document.documentElement.clientHeight - box.offsetHeight) {
                    y = document.documentElement.clientHeight - box.offsetHeight
                }
                if (x <= 0) {
                    x = 0
                }
                if (y <= 0) {
                    y = 0
                }
                box.style.left = x + 'px'
                box.style.top = y + 'px'
            }
        }
        window.onmouseup = function () {
            window.onmousemove = null
        }

        btn.onclick = back
        function back() {
            var len = arr.length - 1, i = 0;
            var time = setInterval(() => {
                box.style.left = arr[i][1] + "px";
                box.style.top = arr[i][0] + "px";
                i++;
                if (i > len) {
                    arr.length = 0
                    clearInterval(time);
                }
            }, 10)
        }
    </script>
</body>

</html>